/** get params in url **/
function getUrlParam(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function getCharSize() {
    var tempDiv = $('<div />').attr({'role': 'listitem'});
    var tempSpan = $('<div />').html('qwertyuiopasdfghjklzxcvbnm');
    tempDiv.append(tempSpan);
    $("html body").append(tempDiv);
    var size = {
        width: tempSpan.outerWidth() / 26,
        height: tempSpan.outerHeight(),
        left: tempDiv.outerWidth() - tempSpan.outerWidth(),
        top: tempDiv.outerHeight() - tempSpan.outerHeight(),
    };
    tempDiv.remove();
    return size;
}

function getWindowSize(dom) {
    var e = window;
    var a = 'inner';
    if (!('innerWidth' in window)) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    var terminalDiv = document.getElementById(dom);
    var terminalDivRect = terminalDiv.getBoundingClientRect();
    return {
        width: terminalDivRect.width,
        height: e[a + 'Height'] - terminalDivRect.top
    };
}

function getTerminalSize(dom) {
    var charSize = getCharSize();
    var windowSize = getWindowSize(dom);
    var cols = Math.floor((windowSize.width - charSize.left) / 10) + 10;
    var rows = Math.floor((windowSize.height - charSize.top) / 17);
    if (cols <= 100) {
        cols = 80;
    }
    return {
        cols: cols,
        rows: rows
    };
}

/** init xterm **/
function initXterm(dom, stdin) {
    var terminalSize = getTerminalSize(dom);
    console.log(terminalSize);
    var cols = terminalSize.cols;
    var rows = terminalSize.rows;

    if (stdin != undefined && stdin == true) {
        stdin = true;
    } else {
        stdin = false;
    }
    // init xterm
    return new Terminal({
        cols: cols,
        rows: rows,
        disableStdin: stdin,
        screenReaderMode: true,
        rendererType: 'canvas',
        convertEol: true
    });
}

/**
 * 关闭ws和xterm
 * @param xterm
 * @param ws
 */
function disconnect(xterm, ws) {
    try {
        if (ws != null) {
            ws.onmessage = null;
            ws.onclose = null;
            ws.close();
            ws = null;
        }
        if (xterm != null) {
            xterm.destroy();
            xterm = null;
        }
        XJJ.msgok('关闭链接成功!');
    } catch (e) {
        XJJ.msger('关闭连接失败，不存在该链接.');
    }
}

//获取数据
function getReturnInfo(ip, port, agentId, cmd, callback) {
    var path = 'ws://' + ip + ':' + port + '/ws';
    if (agentId != 'null' & agentId != "" && agentId != null) {
        path = path + '?method=connectArthas&id=' + agentId;
    }
    var ws;

    try {
        ws = new WebSocket(path);
        if (ws != null) {
            XJJ.msgok("连接成功");
        } else {
            XJJ.msgok("连接失败");
            return;
        }
    } catch (e) {
        XJJ.msger("请检查参数是否正确");
        return;
    }


    ws.onerror = function () {
        ws = null;
        XJJ.msger('连接失败');
    };

    ws.onclose = function (message) {
        if (message.code === 2000) {
            XJJ.msgok(message.reason);
        }
    };

    ws.onopen = function () {
        var i = 0;
        ws.send(JSON.stringify({action: 'resize', cols: 1000, rows: 1000}));
        ws.onmessage = function (event) {
            if (event.type === 'message') {
                var data = event.data;
                if (data.startsWith("[arthas@") && i == 0) {
                    i = i + 1;
                    data = "";
                    ws.send(JSON.stringify({action: 'read', data: cmd + "\r"}));
                }

                if (i > 0) {
                    if (data.startsWith("[arthas@")) {
                        callback(true);
                        disconnect(null, ws);
                        return;
                    }

                    if (data.length > 1 && !data.startsWith("Affect")) {
                        //类详细
                        data = data.replace(/\[[0-9|;]{1,4}m/g, "");
                        callback(data);
                    }
                }
            }
        }
    }
}

function replace(str, substr, newstr) {
    var p = -1; // 字符出现位置
    var s = 0; // 下一次起始位置

    while ((p = str.indexOf(substr, s)) > -1) {
        s = p + newstr.length; // 位置 + 值的长度
        str = str.replace(substr, newstr);
    }
    return str;
}

/**
 *
 * @param dom
 * @param url
 * @param tag
 * @returns {*}
 */
function initArthasConsole(dom, url, tag, stdin) {
    var meteor_websocket = null;
    var meteor_xterm = null;
    var meteor_interval = null;
    try {
        meteor_websocket = new WebSocket(url);
        if (meteor_websocket == null) {
            XJJ.msger("连接失败，请检查账号密码是否正确");
        }
    } catch (e) {
        XJJ.msger("请检查IP或PORT正确");
        return;
    }

    meteor_websocket.onerror = function () {
        meteor_websocket = null;
        XJJ.msger('连接错误');
        if (meteor_interval != null) {
            window.clearInterval(meteor_interval);
        }
    };
    meteor_websocket.onclose = function (message) {
        if (message.code === 2000) {
            XJJ.msger(message.reason);
        }
        if (meteor_interval != null) {
            window.clearInterval(meteor_interval);
        }

    };
    meteor_websocket.onopen = function () {

        meteor_xterm = initXterm(dom, stdin);
        var terminalSize = getTerminalSize(dom);
        meteor_websocket.send(JSON.stringify({
            action: 'resize',
            cols: terminalSize.cols,
            rows: terminalSize.rows
        }));
        meteor_websocket.onmessage = function (event) {
            if (event.type === 'message') {
                data = event.data;
                if (meteor_xterm != null) {
                    meteor_xterm.write(data);
                }
            }
        };

        meteor_xterm.open(document.getElementById(dom));

        meteor_xterm.on('data', function (data) {
            meteor_websocket.send(JSON.stringify({action: 'read', data: data}))
            alert(JSON.stringify({action: 'read', data: data}));
        });

        window.addEventListener('resize', function () {
            terminalSize = getTerminalSize(dom);
            meteor_websocket.send(JSON.stringify({action: 'resize', cols: terminalSize.cols, rows: terminalSize.rows}));
            meteor_xterm.resize(terminalSize.cols, terminalSize.rows);
        });

        meteor_interval = window.setInterval(function () {
            if (meteor_websocket != null) {
                meteor_websocket.send(JSON.stringify({action: 'read', data: ""}));
            }

            if ($("#" + dom).html() == undefined) {
                disconnect(meteor_xterm, meteor_websocket);
            }
        }, 30000);

        if (tag != null || tag != undefined) {
            $("#XjjTab li a[href='#" + tag + "']").click(function () {
                setTimeout(function () {
                    var terminalSize = getTerminalSize(dom);
                    meteor_websocket.send(JSON.stringify({
                        action: 'resize',
                        cols: terminalSize.cols,
                        rows: terminalSize.rows
                    }));
                    meteor_xterm.resize(terminalSize.cols, terminalSize.rows);
                }, 1000)

            })
        }
    };
    return meteor_websocket;
}

function initWebsocketConsole(dom, url, tag,stdin, callback) {
    var meteor_websocket;
    var meteor_xterm;
    var meteor_interval = null;
    try {
        meteor_websocket = new WebSocket(url);
        if (meteor_websocket == null) {
            XJJ.msger("连接失败，请检查账号密码是否正确");
        }
    } catch (e) {
        XJJ.msger("请检查IP或PORT正确");
        return;
    }

    meteor_websocket.onerror = function () {
        meteor_websocket = null;
        XJJ.msger('连接错误');
        if (meteor_interval != null) {
            window.clearInterval(meteor_interval);
        }
    };
    meteor_websocket.onclose = function (message) {
        if (message.code === 2000) {
            XJJ.msger(message.reason);
        }
        if (meteor_interval != null) {
            window.clearInterval(meteor_interval);
        }
        meteor_websocket = null;
    };
    meteor_websocket.onopen = function () {
        meteor_xterm = initXterm(dom,stdin);
        meteor_websocket.onmessage = function (event) {
            if (event.type === 'message') {
                data = event.data;
                if (meteor_xterm != null) {
                    if (null != callback && undefined != callback) {
                        callback(data);
                    }
                    meteor_xterm.write(data);
                }
            }
        };

        meteor_xterm.open(document.getElementById(dom));

        meteor_xterm.on('data', function (data) {
            meteor_websocket.send(data);
        });

        meteor_interval = window.addEventListener('resize', function () {
            var terminalSize = getTerminalSize(dom);
            meteor_xterm.resize(terminalSize.cols, terminalSize.rows);
        });

        $("#XjjTab li a[href='#" + tag + "']").click(function () {
            setTimeout(function () {
                var terminalSize = getTerminalSize(dom);
                meteor_xterm.resize(terminalSize.cols, terminalSize.rows);
            }, 1000)
        })
    };
    return meteor_websocket;
}
